#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash opencv-4.5.5 buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1

yum install -y environment-modules systemd-devel wget
yum install -y cmake python3 python3-numpy libjpeg libtiff giflib gstreamer* libgtk* gtk2-devel libxvidcore* libx264* libgtk-3* gtk3-devel tbb openblas lapack jasper hdf5-devel protobuf
set -e

wget -t 10 -c -P $buildpath https://github.com/opencv/opencv/archive/refs/tags/4.5.5.tar.gz --no-check-certificate
mv $buildpath/4.5.5.tar.gz $buildpath/opencv-4.5.5.tar.gz
wget -t 10 -c -P $buildpath https://github.com/opencv/opencv_contrib/archive/refs/tags/4.5.5.tar.gz --no-check-certificate
mv $buildpath/4.5.5.tar.gz $buildpath/opencv_contrib-4.5.5.tar.gz
cd $buildpath
tar xf opencv-4.5.5.tar.gz
tar xf opencv_contrib-4.5.5.tar.gz
cd opencv-4.5.5
ln -fs /usr/lib64/libz.so.1.2.11 /usr/lib64/libz.so
mkdir -p build
cd build
export CC=`which clang`
export CXX=`which clang++`
export FC=`which flang`
cmake -DCMAKE_BUILD_TYPE=RELEASE \
-DCMAKE_CXX_FLAGS_RELEASE=-O3 --ffp-contract=off \
-DCMAKE_INSTALL_PREFIX=$buildpath/opencv-4.5.5 \
-DOPENCV_EXTRA_MODULES_PATH=$buildpath/opencv_contrib-4.5.5/modules \
-DWITH_EIGEN=ON \
-DWITH_QT=ON \
-DOPENCV_ENABLE_NONFREE=ON \
-DINSTALL_C_EXAMPLES=ON \
-DINSTALL_PYTHON_EXAMPLES=ON \
-DPYTHON3_PACKAGES_PATH=/usr/lib/python3/dist-packages \
-DOPENCV_GENERATE_PKGCONFIG=ON \
-DBUILD_EXAMPLES=OFF ..
make -j$(nproc)
make install
mkdir -p $installpath/opencv-4.5.5 && cp -r $buildpath/opencv-4.5.5/* $installpath/opencv-4.5.5
cat>"$installpath/opencv-4.5.5/opencv_modulefiles"<<EOF
#%Module1.0
conflict opencv
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set OPENCV \$pwd
setenv OPENCV \$OPENCV
prepend-path PATH \$OPENCV/bin
prepend-path LD_LIBRARY_PATH \$OPENCV/lib64
EOF

rm -rf $buildpath/opencv-4.5.5
